var _inherit = require('core/inherit.js');
var _UIContainer = require('component/uicontainer.js');

var _Fragment = require('./fragment.js');

// ==========================
// Pane, used as part of a scene
// ==========================
function Pane() {
    _UIContainer.call(this);
    this.mFragments = [];
}
_inherit(Pane, _UIContainer);
Pane.prototype.removeFragment = function (fragment) {
    for (var i = 0, fs = this.mFragments, l = fs.length; i < l; i++) {
        var frag = fs[i];
        if (frag === fragment) {
            fs.splice(i, 1);
            this.removeChild(fragment.getView());
            break;
        }
    }
};
/**
 * add fragment to under layer
 * @param drawable
 * @returns {*}
 */
Pane.prototype.addFirst = function (drawable) {
    var f = this.addFragment(drawable);
    for (var i = 0; i < this.mChildren.length; i++) {
        if (this.mChildren[i] === drawable) {
            this.mChildren.splice(i, 1);
            break;
        }
    }
    this.mChildren.splice(0, 0, drawable);
    return f;
};
Pane.prototype.findFragment = function (id) {
    for (var i = 0, fs = this.mFragments, l = fs.length; i < l; i++) {
        if (fs[i].getView().getId() == id) {
            return fs[i];
        }
    }
    return null;
};
Pane.prototype.addNotExist = function (drawable) {
    var frag = this.findFragment(drawable.getId());
    if (!frag) {
        this.addFragment(drawable);
    }
};
/**
 * @param drawable
 * @param [clz] use specific class
 */
Pane.prototype.addFragment = function (drawable) {
    var f = new _Fragment(this, drawable);
    this.mFragments.push(f);
    this.addChild(drawable);
    f.resize();
    return f;
};
Pane.prototype.resize = function (w, h) {
    this.setSize.apply(this, arguments);
    for (var i = 0, fs = this.mFragments, l = fs.length; i < l; i++) {
        fs[i].resize();
    }
};
Pane.prototype.forEach = function (fn, bind) {
    bind = bind || this;
    for (var i = 0, fs = this.mFragments, l = fs.length; i < l; i++) {
        fn.call(bind, fs[i], i, fs);
    }
};
Pane.prototype.dumpFragments = function () {
    while (this.mFragments.length) {
        var frag = this.mFragments.pop();
        this.removeChild(frag.getView());
    }
};

// ---------------- export
module.exports = Pane;
Pane.newInstance = function () {
    return new Pane();
};

// ---------------- as pane
Pane.onCreate = function () {
    this.mFragments = [];
};
Pane.asPane = function (clz) {
    var proto = Pane.prototype;
    for (var i in proto) {
        clz.prototype[i] || (clz.prototype[i] = proto[i]);
    }
};
